<{capture name="header"}>
<{script src="coms/dropmenu.js" app='desktop' }>
<{script src="coms/autocompleter.js" app='desktop' }>
<{script src="coms/pager.js" app='desktop' }>
<{/capture}>

<form method="post" id="fm1" action="index.php?app=purchase&ctl=admin_purchase&act=doSave">
  <div class="tableform">
    <h3>新建采购订单</h3>
    <div class="division">
      <h5>基本信息</h5>
      <table border="0" cellspacing="0" cellpadding="0" class="gridlist">
      <thead>
        <tr>
          <td width="10%" align="right" nowrap="nowrap">采购单名称:</td>
          <td colspan="3"><span id="exigence" style="color:red; display:none">！</span>
            <input type="text" class="x-input" size="32" onblur="checkName(this.value);" id="purchase_name" name="purchase_name" value="<{$cur_date}>" />
            <input type="checkbox" name="emergency" value="true" onchange="chgexigence(this);" />
            紧急采购</td>
        </tr>
        <tr>
          <td align="right">供应商:</td>
          <td width="40%"><div style="position:relative;"><{input type="text" id="supplier" name="supplier" vtype="required" value="{$supplier.name}"}>
              <input type="hidden" name="supplier_id" id="supplier_id" value="<{$supplier.supplier_id}>" />
              <span style="color:red;">*</span> <a title="查看供应商列表" class="btn_supplier" target="_blank"><{img id="copy" app="desktop" title="供应商列表" src="bundle/zoom_btn.gif"}></a> </div></td>
          <td width="10%" align="right">到货仓库:</td>
          <td>

            <{if $is_super}>
                <{if count($branch)=='1'}>
                    <{$branch.0.name}>
                    <input type="hidden" id="branch" name="branch" value="<{$branch.0.branch_id}>" />
                <{else}>
                    <{input type="select" name="branch" id="branch" vtype="required" required="true" rows=$branch valueColumn="branch_id" labelColumn="name" value="{$branchid}"}> <span style="color:red">*</span>
                <{/if}>
            <{else}>
                <{if !$branch_list}>
                    <font color="red">* 当前没有操作仓库的权限，请联系管理员分配。  *</font>
                    <script>
                       $$("input","button","select").set('disabled','disabled');
                    </script>
                <{else}>
                    <{if count($branch_list)==1}>
                        <{$branch_list.0.name}>
                        <input type="hidden" id="branch" name="branch" value="<{$branch_list.0.branch_id}>" />
                    <{else}>
                        <{input type="select" id="branch" name="branch" vtype="required" required="true" rows=$branch_list valueColumn="branch_id" labelColumn="name" value="{$branchid}"}> <span style="color:red">*</span>
                    <{/if}>
                <{/if}>
            <{/if}>
        </tr>
        <tr>
          <td align="right">采购方式:</td>
          <td><input type="radio" name="type" value="cash" <{if $po_type=='cash'}>checked<{/if}> onclick="prichange('1')" /> 现购 <input type="radio" name="type" value="credit" <{if $po_type=='credit' or $po_type==''}>checked<{/if}> onclick="prichange('2')" /> 赊购</td>
          <td align="right" nowrap="nowrap" title="一次性物流费用">物流费用:</td>
          <td><input type="text" vtype="number" class="x-input" name="d_cost" size="6"/>
            元</td>
        </tr>
        <tr>
          <td align="right"><span class="endd" style="display:none">预付款:</span></td>
          <td><span class="endd" style="display:none">
            <input type="text" id="price" vtype="number" class="x-input" name="price" size="6"/>
            元</span></td>
          <td align="right" nowrap="nowrap">预计到货天数:</td>
          <td><input type="hidden" id="arrive" name="arrive" value="" />
            <input type="text" size="2" id="arrive_days" class="x-input" name="arrive_days" vtype="required" onchange="pushDate(this);" maxlength="3" />
            天 <span style="color:red">*</span> <b id="pushdate"></b></td>
        </tr>
        </thead>
      </table>
      <h5 style="margin-top:10px;">采购商品</h5>
      <{button label="供应商频道" id="supplier-find-btn" }>
      <{button label="基础物料库频道" id="purchase-find-btn" }>
      <span id='pfba'>
      <label>按基础物料编码索引：</label>
      <input type="text" name="bn" />
      </span> <span id='pfba2'>
      <label>按基础物料名称索引：</label>
      <input type="text" name="name" />
      </span>
      <table class="gridlist" id="purchase_table"  style="margin:4px 0;">
        <thead>
          <tr>
            <th style="width:35px;">删除</th>
            <th>基础物料编码</th>
            <th>基础物料名称</th>
            <th>规格</th>
            <th>条形码</th>
            <th>数量</th>
            <th>单价</th>
          </tr>
        </thead>
        <tbody id="dataNode">
          <tr>
            <td colspan="7" style="padding:0;"><div class="note" style="margin:0;"> 暂无采购货品信息 </div></td>
          </tr>
        </tbody>
      </table>
      <{button type="button" class="btn btn-primary" id="purchase-delall-btn" label="全选" }>
      <{button label="删除选中" class="btn btn-primary" id="purchase-del-btn"}> </div>
    <table width="100%" border="0" cellpadding="0" cellspacing="0" style="margin-top:10px;">
      <tr>
        <td width="10%" align="right">备注:</td>
        <td align="left"><textarea id="memo" maxth="255" rows="3" cols="80%" name="memo" type="textarea"></textarea></td>
      </tr>
      <tr>
        <td align="right">经办人:</td>
        <td align="left"><input name="operator" type="text" value="<{$operator}>" size="15" vtype="required"/></td>
      </tr>
    </table>
    <div id="cc" class="noprint table-action"> <{button type="button" class="btn" id="purchase-save-btn" label="保 存"}> &nbsp; <{button type="button" class="btn" id="return-btn" label="关 闭" onclick="javascript:void(window.close());"}></div>
  </div>
</form>
<script>
(function(){

    $E('#arrive_days').set("value",'<{$supplier.arrive_days}>');
    pushDate($('arrive_days'));

   var callurl='index.php?app=purchase&ctl=admin_purchase&act=getProducts',store=[];


   new Request({url:'index.php?app=purchase&ctl=admin_purchase&act=getSafeStock&p[0]=<{$filter.supplier_id}>&p[1]=<{$filter.branch_id}>&p[2]=<{$filter.bn}>&p[3]=<{$product_ids}>',
   onComplete:function(rs){
       rs=JSON.decode(rs);
       store.combine(rs);
       createProduct(store);
   }}).send();

   var options={
        'getVar':'bn',
        'fxOptions':false,
        callJSON:function(){return window.autocompleter_json;},
        injectChoice:function(json){
			var choice = new Element('li', {'html': this.markQueryValue(json[this.options.getVar])});
			choice.store('_data',json);
			choice.inputValue = json[this.options.getVar];
			this.addChoiceEvents(choice).inject(this.choices);
        },
        onHide:function(){
                if(!this.selected)return ;
               var json=this.selected.retrieve('_data');
                json=$splat(json);
                init(json);
                MessageBox.success('加载商品成功!!');
       },onFocus:function(ipt){
                ipt.value='';
       }
   }
   new Autocompleter.script($E('#supplier'),"index.php?app=purchase&ctl=admin_supplier&act=getSupplier", {
		'getVar':'name',
		'fxOptions':false,
		'callJSON':function(){return window.autocompleter_json},
		injectChoice:function(json){
			var brief=json["brief"]?"("+json["brief"]+")":"";
			var choice = new Element('li', {'html': this.markQueryValue(json[this.options.getVar]+brief)});
            choice.store('_data',json);
			choice.inputValue = json[this.options.getVar];
			this.addChoiceEvents(choice).inject(this.choices);
			$('supplier_id').set("value",json["supplier_id"]);
			$('arrive_days').set("value",json["arrive_days"]);
			pushDate($('arrive_days'));
        },
        onHide:function(){
          if(!this.selected)return;
		  var json=this.selected.retrieve('_data');
          $('supplier_id').set("value",json["supplier_id"]);
        }
	});
   new Autocompleter.script($E('#pfba input'),callurl, options);
   new Autocompleter.script($E('#pfba2 input'),callurl,$merge(options,{'getVar':'name'}));

    var tpl='<tr key="{product_id}" id="product_{product_id}"><td><input type="checkbox" key="state"  {state} value="{product_id}"></td>'
        +'<td>{bn}</td><td >{name}</td><td>{spec_info}</td><td>{barcode}</td>'
		+'<td><input id="num_{product_id}" type="text" value="{num}" key="num" vtype="number&amp;&amp;required" tname="at[_PRIMARY_]"  size="10">'
        +'<a onclick="setNums({product_id});"><img align="absmiddle" src="<{$env.app.res_url}>/copy.png" /></a>'
        +'</td>'
        +'<td><input type="text" vtype="number&amp;&amp;required"  tname="pr[_PRIMARY_]" key="price" value="{price}" size="8">元</td></tr>';

    $('purchase-find-btn').addEvent('click',function(e){
        var url='index.php?app=desktop&act=alertpages&goto='+encodeURIComponent('index.php?app=purchase&ctl=admin_purchase&act=findMaterial');
		Ex_Loader('modedialog',function() {
			new finderDialog(url,{params:{url:callurl,name:'product_id[]'},width:1000,height:660,
			onCallback:function(rs){
			  if(!rs)return;
			  rs=JSON.decode(rs);
			  init(rs);
			}});
		});
    });

    //从供应商查找商品
    $('supplier-find-btn').addEvent('click',function(e){
        if ($("supplier_id").get("value").trim().length===0){
			$('supplier').addClass("error_supplier");
			MessageBox.error("请先填写正确的供应商！");
            return false;
        }
		$('supplier').removeClass("error_supplier");
        var supplier_id = $('supplier_id').value;
        var url='index.php?app=desktop&act=alertpages&goto='+encodeURIComponent('index.php?app=purchase&ctl=admin_purchase&act=findMaterial&p[0]='+supplier_id);
		Ex_Loader('modedialog',function() {
			new finderDialog(url,{params:{url:callurl,name:'product_id[]'},width:1000,height:660,
			onCallback:function(rs){
					if(!rs)return;
					rs=JSON.decode(rs);
					init(rs);
			}});
		});
    });


	$E(".btn_supplier").addEvent('click',function(e){
		var url='?app=desktop&act=alertpages&goto='+encodeURIComponent("index.php?app=purchase&ctl=admin_supplier&singleselect=1");
		Ex_Loader('modedialog',function() {
			new finderDialog(url,{params:{url:'index.php?app=purchase&ctl=admin_supplier&act=getSupplierById',name:'id',type:'radio'},handle:'supplier',width:1000,height:500});
		});
	});

    var pag;
    function createProduct(data){
        pag=new PageData(tpl,data,{'updateMain':$('dataNode'),'pageNum':10,
        'onShow':function(){
            var _this=this;
             $$('#dataNode input[type]').addEvent('change',function(e){
                 var pid=this.getParent('tr').get('key'),value=this.value;
                 if(this.get('type')=='checkbox'){
                    if(!this.checked)$('purchase-delall-btn').checked=false;
                     value=this.checked?'checked':'';
                 }
                _this.editData(pid,[this.get('key'),value]);
            });

			var state=this.curdata.every(function(d){return d['state']=='checked';});

			$('purchase-delall-btn').checked=!state?false:true;

			attachEsayCheck($('dataNode'),'input[type=checkbox]');

            $E('#dataNode tr') && $E('#dataNode tr').getElement('input[key^=num]').focus();
			$ES('input[tname^=at]').addEvent('keypress',function(e){
                if(e.code==13)$E('#pfba input').focus();
            });
        }
        });
    }   
    function init(rs){
        var tmparr=findProduct(rs,'product_id');
         store.unshift.apply(store,tmparr.reverse());
         createProduct(store);

    };
    function findProduct(arr,PRIMARY){
        if(!store.length)return arr;
        store.each(function(a){
            arr.each(function(b){
                if(a[PRIMARY]==b[PRIMARY])arr.erase(b);
            });
        });
        return arr;
    }

    function delProduct(obj,arr){
        arr.each(function(d){obj.delData(d);});
    }

    $('purchase-delall-btn').addEvent('click',function(e){
        //var value=this.checked?'checked':'';
        if(!pag||!pag.curdata)return;
		pag.curdata.each(function(d){
            pag.editData(d['product_id'],['state','checked']);
        });
        pag.render(pag.options.current);
    });

	$('purchase-del-btn').addEvent('click',function(e){
		var delarr=[];
		pag.data.each(function(d){
			if(d['state']&&d['state']=='checked'){delarr.push(d['product_id']);}
		});
		if(delarr.length&&confirm('确认删除吗？'))
		delProduct(pag,delarr);
	});

    $('purchase-save-btn').addEvent('click',function(e){
        var form=this.getParent('form');
        if(pag){
            var data=pag.toHideInput($('dataNode').getElement('tr'));
             form.store('target',{extraData:data,
              onRequest:function(){
                 $('purchase-save-btn').set('disabled', 'true');
              },
              onComplete:function(jsontext){
                  try{
                      var json = Json.evaluate(jsontext);
                      if (typeof(json.error) != 'undefined'){
                          $('purchase-save-btn').set('disabled', '');  
                      }else{
                          $('purchase-save-btn').set('disabled', 'true');
                          window.close();
                      }
                  }catch(e){}
              }});
        }
        form.fireEvent('submit',e);
    });
})();

// 采购商品的数量复制到当前页面的所有行
function setNums(pid){
    var inputs = $E('#dataNode').getElementsByTagName('input');
    var val = $E('#num_'+pid).value;
    for(var i=0;i<inputs.length;i++) {
        if((i%3)==1) {
            inputs[i].value = val;
            inputs[i].fireEvent('change');
        } 
    }
}

function chgexigence(o){
	o.checked?$("exigence").setStyle('display',""):$("exigence").setStyle('display',"none");
}
function validSupplier(element){
	element=$(element);
	new Element('span',{'class':'error caution notice-inline','html':'本项必填'}).injectAfter(element);
	element.removeEvents('blur').addEvent('blur',function(){
		//element.setStyle("background","#FBE3E4");
	   if(validate(element)){
		   //element.setStyle("background","#fff");
		   element.removeEvent('blur',arguments.callee);
	   }
	});
}
//validSupplier('supplier');

function pushDate(o){
	if(o.value!==""){
		if(/^\d*$/.test(o.value)){
			if (o.getNext('.error')) o.getNext('.error').dispose();
			$("pushdate").set("text",(new Date(Date.parse(new Date())+86400000 * o.value.toInt())).toLocaleDateString());
			//$("arrive").set("value", new Date(new Date.parse(new Date())+86400000 * o.value)) ;
		}
		else o.value="";
	}
	else $("pushdate").empty();
}

function prichange(ss){
	if (ss == 1){
		$$('.endd').setStyle('display','none');
		$('price').set('value', '');
	}else{
		$$('.endd').setStyle('display', '');
	}
}

function checkName(thisval){
	if(/!|！/.test(thisval)){
		var val = thisval.replace("!","");
		val = val.replace("！","");
		$('purchase_name').set('value', val);
    }
}

//赊购方式触发事件
<{if $po_type=='credit' or $po_type==''}>
prichange('2');
<{/if}>
</script>
